/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.projeto.infra;

import com.projeto.business.controller.EventController;
import com.projeto.persistence.Event;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;
import javax.ejb.EJB;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;


/**
 *
 * @author fneves
 */
public class PrincipalFilter implements Filter{

    @EJB
    EventController eventBean;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        if(req.getSession().getAttribute("LOGGED") == null)
        {
            String user = req.getRemoteUser() != null ? req.getRemoteUser() : "NULL";
            String host = req.getRemoteHost() != null ? req.getRemoteHost() : "NULL";
            String address = req.getRemoteAddr() != null ? req.getRemoteAddr() : "NULL";

            Event e = new Event();
            e.setId(UUID.randomUUID().toString());
            e.setBefore("Host: " + host + " , IP: " + address);
            e.setCreateDt(new Date());
            e.setCreatedBy(user);
            e.setEvent(Event.EVENT.LOGIN);
            eventBean.save(e);
            req.getSession().setAttribute("LOGGED", e);
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        
    }               
}
